package xyz.quanguanjia.masterboy;

import android.graphics.Color;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;

public class MBDToolbarUtils {

    public static void setCenterTitle(Toolbar toolbar, CharSequence title) {
        if (toolbar != null) {
            // 找到 toolbar_title 的 TextView
            TextView titleTextView = findTitleTextView(toolbar);

            // 如果找到了 TextView，则设置标题
            if (titleTextView != null) {
                titleTextView.setText(title);
            }
        }
    }

    public static void backButtonClicked(Toolbar toolbar, final Runnable action) {
        if (toolbar != null) {
            ImageView backButton = findBackButton(toolbar);
            if (backButton != null) {
                backButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (action != null) {
                            action.run();
                        }
                    }
                });
            }
        }
    }

    private static TextView findTitleTextView(Toolbar toolbar) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View child = toolbar.getChildAt(i);
            if (child instanceof TextView && child.getId() == R.id.toolbar_title) {
                return (TextView) child;
            }
        }
        return null;
    }

    private static ImageView findBackButton(Toolbar toolbar) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View child = toolbar.getChildAt(i);
            if (child instanceof ImageView && child.getId() == R.id.img_toolbar_back_arrow) {
                return (ImageView) child;
            }
        }
        return null;
    }

    public static void toolButtonClicked(Toolbar toolbar, int buttonId, View.OnClickListener onClickListener) {
        Object imageView = toolbar.findViewById(buttonId);
        if (imageView instanceof ImageView) {
            ((ImageView) imageView).setOnClickListener(onClickListener);
        } else if (imageView instanceof Button) {
            ((Button) imageView).setOnClickListener(onClickListener);
        } else if (imageView instanceof TextView) {
            ((TextView) imageView).setOnClickListener(onClickListener);
        }
    }
}
